package io.geekidea.boot.generator.query;

import com.baomidou.mybatisplus.generator.config.querys.SqlServerQuery;

/**
 * @author geekidea
 * @date 2022/7/7
 **/
public class CustomSqlServerQuery extends SqlServerQuery {

    @Override
    public String tableFieldsSql() {
        return "SELECT cast(a.name AS VARCHAR(500))         AS TABLE_NAME, " +
                "       cast(b.name AS VARCHAR(500))         AS COLUMN_NAME, " +
                "       cast(c.VALUE AS NVARCHAR(500))       AS COMMENTS, " +
                "       cast(sys.types.name AS VARCHAR(500)) AS DATA_TYPE, " +
                "       (SELECT CASE count(1) WHEN 1 then 'PRI' ELSE '' END " +
                "        FROM syscolumns, " +
                "             sysobjects, " +
                "             sysindexes, " +
                "             sysindexkeys, " +
                "             systypes " +
                "        WHERE syscolumns.xusertype = systypes.xusertype " +
                "          AND syscolumns.id = object_id(a.name) " +
                "          AND sysobjects.xtype = 'PK' " +
                "          AND sysobjects.parent_obj = syscolumns.id " +
                "          AND sysindexes.id = syscolumns.id " +
                "          AND sysobjects.name = sysindexes.name " +
                "          AND sysindexkeys.id = syscolumns.id " +
                "          AND sysindexkeys.indid = sysindexes.indid " +
                "          AND syscolumns.colid = sysindexkeys.colid " +
                "          AND syscolumns.name = b.name)     as 'KEY', " +
                "       b.is_identity                           isIdentity, " +
                "       b.max_length, " +
                "       b.is_nullable, " +
                "       (SELECT  c.name " +
                "            FROM    sys.tables t " +
                "                    INNER JOIN sys.columns c ON t.object_id = c.object_id " +
                "                    INNER JOIN sys.default_constraints dc ON c.default_object_id = dc.object_id " +
                "            WHERE   t.name = a.name and b.name = c.name) as default_value " +
                "FROM (select name, object_id from sys.tables UNION all select name, object_id from sys.views) a " +
                "         INNER JOIN sys.columns b ON b.object_id = a.object_id " +
                "         LEFT JOIN sys.types ON b.user_type_id = sys.types.user_type_id " +
                "         LEFT JOIN sys.extended_properties c ON c.major_id = b.object_id AND c.minor_id = b.column_id " +
                "WHERE a.name = '%s' " +
                "  and sys.types.name != 'sysname'";
    }

    @Override
    public String[] fieldCustom() {
        return new String[]{"max_length", "is_nullable", "default_value"};
    }

}
